package ginplus

import (
	"gitee.com/hongzhaomin/hzm-common-go/coll"
	"github.com/gin-gonic/gin"
	"reflect"
)

func NewHandlerMappingWrapper(mapping *HandlerMapping, ctx *gin.Context, rvParams []reflect.Value) *HandlerMappingWrapper {
	wrapper := &HandlerMappingWrapper{
		HandlerMapping: mapping,
		ctx:            ctx,
	}
	if len(rvParams) > 0 {
		args := make([]any, len(rvParams))
		for i, rvParam := range rvParams {
			if rvParam.IsValid() {
				// 当方法返回值定义为指针类型时，返回结果为nil，此时的nil并非我们理解的nil，用 val.Interface() == nil 为false
				// 这里需要判断下是否为nil，因为后面需要判断nil
				canCallIsNilKinds := []reflect.Kind{reflect.Chan, reflect.Func, reflect.Map,
					reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Slice}
				if coll.Contains(canCallIsNilKinds, rvParam.Kind()) && rvParam.IsNil() {
					args[i] = nil
				} else {
					// 不为nil，取真实值
					args[i] = rvParam.Interface()
				}
			}
		}
		wrapper.args = args
	}
	return wrapper
}

type HandlerMappingWrapper struct {
	*HandlerMapping
	ctx  *gin.Context
	args []any
}

func (my *HandlerMappingWrapper) GetFullPath() string {
	return my.ctx.FullPath()
}

func (my *HandlerMappingWrapper) Args() []any {
	return my.args
}

func (my *HandlerMappingWrapper) QueryParam(name string) string {
	return my.ctx.Query(name)
}

func (my *HandlerMappingWrapper) GetHeader(name string) string {
	return my.ctx.GetHeader(name)
}

func (my *HandlerMappingWrapper) Cookie(name string) (string, error) {
	return my.ctx.Cookie(name)
}

func (my *HandlerMappingWrapper) GetResponse() gin.ResponseWriter {
	return my.ctx.Writer
}

func (my *HandlerMappingWrapper) HTML(code int, name string, obj any) {
	my.ctx.HTML(code, name, obj)
}

func (my *HandlerMappingWrapper) JSON(code int, obj any) {
	my.ctx.JSON(code, obj)
}
